import java.io.*;
import java.util.*;



public class Proj350 {

	public static SimpleLogger logger = new SimpleLogger();
	
	/**
	 * Main function
	 * @param args - configuration file name, input file name
	 */
	public static void main(String[] args) {
		
		boolean flagDeleteDB = false;
		
		//Parse input files
		Parser parser = new Parser();
		parser.parseConfig("config.txt");
		parser.parseInput("input.txt");
				
		//Create a new peer according to parsed data
		Peer myPeer = new Peer(parser.get_firstPeer(), parser.get_firstIP(), 
				parser.get_firstTCP(),parser.get_firstUDP(), parser.get_firstPhone(), 
				parser.get_firstEmail(), parser.get_firstBuffer(), 
				parser.get_firstPicName(), parser.get_firstPicSize(), parser.get_mss(),
				parser.get_updateFrequency(), parser.get_N(),
				parser.get_peerName(), parser.get_ip(), parser.get_tcp(), parser.get_udp());
		
		Queue<String> commands = parser.get_queue();
		
		try {
			myPeer.initialize();
		} catch (IOException ex) {
			Proj350.logger.logError("Error reading picture file");
			Proj350.logger.close();
			System.exit(-1);
		}
		
		//Executing commands
		while (!commands.isEmpty()) {
			String command = commands.poll();
			
			String[] parsed = command.split("\\&|:|\\(|,|\\$|\\)");
			
			if (parsed[0].equals("run")) { //Run command
				new Thread(myPeer).start();
				try {
					Record owner = myPeer.getOwner();
					String logMessage = String.format("%s\n$peername:%s\n$ip:%s\n$udp:%s\n$tcp:%s\n$phone:%s\n$email:%s\n$pic:%s\n$picSize:%s",
							command, owner.get_peerName(), 
							owner.get_ip(), owner.get_udp(), owner.get_tcp(),
							owner.get_phone(), owner.get_email(), myPeer.getPictureFileName(), owner.get_picSize());
					logger.logCommand(logMessage); //Log command
					
					Thread.sleep(Integer.parseInt(parsed[1]) * 1000);
					myPeer.stop();
					Thread.sleep(1500);
				} catch (InterruptedException ex) {}
			} else if (parsed[0].equals("sleep")) { //Sleep command
				logger.logCommand(command); //Log command
				try {Thread.sleep(Integer.parseInt(parsed[1]) * 1000);}
				catch (InterruptedException ex) {}
			} else if (parsed[0].equals("updatedata")) { //Update owner peer data
				try {
					logger.logCommand(command); //Log command
					myPeer.UpdateDB(parsed);
				} catch (IOException ex) {
					Proj350.logger.logError("Error reading new picture file");
					Proj350.logger.close();
					System.exit(-1);
				}
			} else if (parsed[0].equals("deletedb")) {
				if (parsed[1].equals("1")) {
					logger.logCommand(command); //Log command
					myPeer.deleteDBFile();
					flagDeleteDB = true;
					myPeer.createDB();
				} else if (parsed[1].equals("0"))
					logger.logCommand(command); //Log command
				else
					logger.logError("wrong command"); //Log error
				
			} else if (parsed[0].equals("SHUTDOWN")) {
				logger.logCommand(command); //Log command
				commands.clear();
				try {
					if (!flagDeleteDB)
						myPeer.saveDB();
				} catch (FileNotFoundException ex) {
					Proj350.logger.logError("Error saving DB to hard drive");
				} catch (IOException ex) {
					Proj350.logger.logError("Error saving DB to hard drive");
				}
			}
		}
		
		//Stop current peer
		myPeer.stop();
		logger.close(); 
	}
}
